export default class RandomFetcher<T extends Record<string, any>> {
  private uniqueKey: keyof T = 'id' as keyof T
  private indices: (string|number)[];
  private currentIndex: number;
  private resourceData: T[];

  constructor(data:T[], uniqueKey: keyof T = 'id' as keyof T) {
    this.uniqueKey = uniqueKey;
    this.resourceData = [...data];
    this.indices = this.getIds();
    this.shuffleIndices();
    this.currentIndex = 0;
  }

  private shuffleIndices() {
    for (let i = this.indices.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [this.indices[i], this.indices[j]] = [this.indices[j], this.indices[i]];
    }
  }

  public getIds() {
    return this.resourceData.map((item:T) => item[this.uniqueKey]);
  }

  public getInfo(uniqueValue: string|number):T {
    return (this.resourceData.find(item => item[this.uniqueKey] === uniqueValue) || {
      title: '暂无数据'
    }) as T
  }

  public getNext(): T {
    if (this.currentIndex >= this.indices.length) {
      this.shuffleIndices();
      this.currentIndex = 0;
    }
    const uniqueValue = this.indices[this.currentIndex++];
    return this.getInfo(uniqueValue);
  }
}
